package logic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.log4j.Logger;

import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by wrs on 2019/6/3,10:35
 * projectName: Testz
 * packageName: comtest.example.admin.netty.server
 */
public class NettyServer {

    // 配置信息
    private final ConfigInfo configInfo = ConfigInfo.getInstance();

    private int port = configInfo.serverPort;

    /*//维护设备连接的map 用于推送消息
    private ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>();
 
    public void setChannel(String name, Channel channel) {
        this.channelMap.put(name, channel);
    }
 
    public ConcurrentHashMap<String, Channel> getChannelMap() {
        return this.channelMap;
    }*/

    // 工具类对象
    private final Utils utils = new Utils();

    // 日志对象
    private final static org.apache.log4j.Logger logger = Logger.getLogger(NettyServer.class);

    //发送消息给下游设备
    /*public boolean writeMsg(String clientName,String msg) {
        boolean errorFlag = false;
        Map<String, Channel> channelMap = getChannelMap();
        if (channelMap.size() == 0) {
            return true;
        }
        try {
            Channel channel = channelMap.get(clientName);

            if (configInfo.encoderStyle == 1) {
                //logger.info("发送数据："+msg);
                // 字节数组传输
                byte[] sByte = utils.hexStringToBytes(msg);
                ByteBuf byteBuf = Unpooled.wrappedBuffer(sByte);
                // 发送消息
                channel.writeAndFlush(byteBuf);
            } else {
                // 发送字符串消息
                channel.writeAndFlush(msg);
            }
        } catch (Exception e) {
            errorFlag = true;
        }
        return errorFlag;
    }*/
 
    public void bind() {
        System.out.println("service start successful");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //特殊分隔符
                        /*pipeline.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                                Unpooled.copiedBuffer(System.getProperty("line.separator").getBytes())));
                        pipeline.addLast("decoder", new StringDecoder());
                        pipeline.addLast("encoder", new StringEncoder());*/

                        if (configInfo.encoderStyle == 1) {
                            // 字节数组传输
                            logger.info("===================" + configInfo.byteOrder);
                            //pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 0xffff, 4, 2, 0, 0, true));
                            if (configInfo.byteOrder == 1) {
                                logger.info("。。。。。。。。。。。。。。。。" + configInfo.byteOrder);
                                // 小端字节顺序
                                pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 0xffff, 4, 2, 0, 0, true));
                            } else {
                                // 大端字节顺序
                                pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, 0xffff, 4, 2, 0, 0, true));
                            }
                        } else {
                            // 字符串传输
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                        }

                        pipeline.addLast("handler", new NettyServerHandler(NettyServer.this));
                    }
                });
        try {
            ChannelFuture f = bootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
